
package com.spring.registry;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;


/**
 * @描述:服务注册
 * @作者:Marks
 * @日期:14:56 2018-10-14
 * @版权:
 */

public class RegisterCenterImpl implements IRegisterCenter {

    //操作zk
    private CuratorFramework curatorFramework;

    {
        //根据Zkconfig中的字符串初始化curatorFramework
        curatorFramework = CuratorFrameworkFactory.builder().connectString(ZkConfig.CONNECTION_STR).sessionTimeoutMs(4000).retryPolicy(new ExponentialBackoffRetry(1000, 10)).build();
        curatorFramework.start();
    }

    @Override
    public void register(String serviceName, String serviceAddress) {
        //节点路径
        String servicePath = ZkConfig.ZK_REGSITER_PATH + "/" + serviceName;
        try {
            if (curatorFramework.checkExists().forPath(servicePath) == null) {
                curatorFramework.create().creatingParentsIfNeeded()
                        .withMode(CreateMode.PERSISTENT)
                        .forPath(servicePath, "0".getBytes());
            }
            String addressPath = servicePath + "/" + serviceAddress;
            String rsNode = curatorFramework.create().withMode(CreateMode.EPHEMERAL)
                    .forPath(addressPath, "0".getBytes());

            System.out.println("服务注册成功"+rsNode);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
